/**
 * Created by John on 2016/7/14.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        firstIsALastIsVowel(collection);
        close();
    });
});

function firstIsALastIsVowel(collection) {
    var key = {first: true, last: true};
    var cond = {first: 'a', last: {$in: ['a', 'e', 'i', 'o', 'u']}};
    var initial = {count: 0};
    var reduce = function (obj, prev) {
        prev.count++;
    };

    var callback = function (err, items) {
        console.log();
        console.log('A words grouped by first and last letter that end with al vowel:');
        displayGroup(items);
        firstLetterTotals(collection);
    };

    collection.group(key, cond, initial, reduce, callback);
}

function firstLetterTotals(collection) {
    var key = {first: true};
    var cond = {};
    var initial = {vowels: 0, cons: 0};
    var reduce = function (obj, prev) {
        prev.vowels += obj.stats.vowels;
        prev.cons += ojb.stats.consonants;
    };

    var finalize = function (obj) {
        obj.total = obj.vowels + obj.consonants;
    };

    var callback = function (err, items) {
        console.log();
        console.log('Words grouped by first letter with totals:');
        displayGroup(items);
    };

    collection.group(key, cond, initial, reduce, finalize, callback);
}

function displayGroup(results) {
    for (var i in results) {
        console.log(results[i]);
    }
}

function close() {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}